import { create, getList, update } from '@/api/user';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Form, Input, Modal, Table, message } from 'antd';
import { useEffect, useState } from 'react';

export default () => {
  const [data, setData] = useState([]);
  const [open, setOpen] = useState(false);
  const [editRow, setEditRow] = useState(null);

  const [form] = Form.useForm();

  const toggle = async (record) => {
    const resp = await update({ ...record, state: record.state == 1 ? 0 : 1 });
    if (resp.code === 0) {
      message.success('操作成功');
      init();
    } else {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户id',
    },
    {
      key: 'name',
      dataIndex: 'name',
      title: '昵称',
    },
    {
      key: 'user_name',
      dataIndex: 'user_name',
      title: '用户名',
    },
    {
      key: 'state',
      dataIndex: 'state',
      title: '是否可用',
      render: (_) => {
        return _ == 1 ? '使用中' : '禁用';
      },
    },
    {
      key: 'action',
      dataIndex: 'action',
      title: '操作',
      width: 200,
      render: (_, record) => {
        return (
          <div>
            <Button
              type="primary"
              onClick={() => {
                setEditRow(record);
                setOpen(true);
                form.resetFields();
                form.setFieldsValue(record);
              }}
            >
              编辑
            </Button>
            {record.state == 1 && (
              <Button type="primary" danger className="ml10" onClick={() => toggle(record)}>
                禁用
              </Button>
            )}
            {record.state == 0 && (
              <Button type="primary" className="ml10" onClick={() => toggle(record)}>
                启用
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  const init = async () => {
    const resp = await getList();
    console.log('[resp]', resp);
    setData(resp?.data?.list || []);
  };

  const formRules = {
    name: [
      {
        required: true,
        message: '昵称不能为空',
      },
    ],
    user_name: [
      {
        required: true,
        message: '账号不能为空',
      },
      {
        pattern: /^[a-zA-Z0-9_-]{5,20}$/, // 假设账号长度为5-20个字符，只包含字母、数字、下划线和短横线
        message: '长度为5-20个字符，只包含字母、数字、下划线和短横线',
      },
    ],
    password: [
      {
        required: true,
        message: '密码不能为空',
      },
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, // 密码至少8-20个字符，至少包含一个字母和一个数字
        message: '密码至少8-20个字符，至少包含一个字母和一个数字',
      },
    ],
  };

  const createOrUpdateUser = () => {
    form.validateFields().then(async (values) => {
      console.log('values', values);
      let resp;
      if (editRow?.id) {
        resp = await update({ ...editRow, ...values });
      } else {
        resp = await create(values);
      }
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success(editRow?.id ? '编辑成功' : '添加成功');
        init();
        setOpen(false);
        form.resetFields();
      } else {
        message.error(editRow?.id ? '编辑失败，请重试' : '添加失败，请重试');
      }
    });
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer>
      <Modal
        onOk={createOrUpdateUser}
        title={editRow?.id ? `编辑用户` : `新增用户`}
        open={open}
        onCancel={() => {
          form.resetFields();
          setOpen(false);
        }}
      >
        <Card>
          <Form
            form={form}
            labelCol={{
              span: 4,
            }}
            initialValues={editRow || {}}
          >
            <Form.Item label="昵称" name={'name'} rules={formRules.name}>
              <Input></Input>
            </Form.Item>
            <Form.Item label="用户名" name={'user_name'} rules={formRules.user_name}>
              <Input></Input>
            </Form.Item>
            <Form.Item label="密码" name={'password'} rules={formRules.password}>
              <Input type="password"></Input>
            </Form.Item>
          </Form>
        </Card>
      </Modal>

      <div className="flex-bt mb10">
        <div></div>

        <Button type="primary" onClick={() => setOpen(true)}>
          新增
        </Button>
      </div>

      <Table columns={columns} dataSource={data}></Table>
    </PageContainer>
  );
};
